package com.example.service;

import com.example.constant.PathConstant;
import com.example.entity.Message;
import com.example.utils.PythonExecuteUtil;
import com.example.utils.tempFileUtil;
import jakarta.annotation.Resource;
import org.json.JSONArray;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.UUID;

/**
 * @Author: 张比特
 * @Data: 2025/2/10 下午5:21
 * @Version: v1.0.0
 * @Description: TODO 行人重识别service
 **/

@Service
public class ReIDService {

    @Resource
    private MessageService messageService;

    /**
     * 上传照片时进行重识别
     * @param file
     * @return
     * @throws IOException
     */
    @Async
    public void Person_ReID_Identification(MultipartFile file, String uid) throws IOException {

        // 创建临时文件
        Path YOLOV7_SOURCE = tempFileUtil.createTempFile(UUID.randomUUID().toString(),".png");
        // 将上传的文件存储到临时文件中
        file.transferTo(YOLOV7_SOURCE);
        /**
         * TODO YOLOv7标记
         * 参数说明
         * - 脚本路径
         * - 权重路径
         * - source路径
         * - target路径
         */
        PythonExecuteUtil.executeYOLOv7Script(PathConstant.YOLOV7_PATH, PathConstant.YOLOV7_WEIGHTS, YOLOV7_SOURCE.toString(), PathConstant.YOLOv7_SOURCE);
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            /**
             * 线程休眠十秒，为python写入文件做缓冲
             */
            e.printStackTrace();
        }
        /**
         * TODO 将标记后的图片与视频做对比
         */
        JSONArray resultArray = PythonExecuteUtil.executeFeatureExtractionScript(PathConstant.FEATURE_EXTRACTION_PATH, PathConstant.FEATURE_EXTRACTION_TARGET ,PathConstant.YOLOv7_SOURCE + File.separator + "exp");
        /**
         * TODO 销毁target中的所有文件
         */
        tempFileUtil.deleteTempDirectory(Path.of(PathConstant.YOLOv7_SOURCE));
        /**
         * TODO 如果匹配到了数据，则向用户发送消息
         * 构造一个消息
         *
         */
        Message message = new Message();
        // 由管理员发送消息
        message.setSender(205);
        message.setReceiver(Integer.parseInt(uid));
        message.setTitle("AI匹配结果通知");
        message.setType("FEEDBACK");
        message.setContent(resultArray.toString());
        message.setIsRead("0");
        messageService.createMessage(message);
    }
}
